<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,guava,">










<meta name="description" content="[Google Guava] 11-事件总线原文链接 译文连接 译者：沈义扬 传统上，Java的进程内事件分发都是通过发布者和订阅者之间的显式注册实现的。设计EventBus就是为了取代这种显示注册方式，使组件间有了更好的解耦。EventBus不是通用型的发布-订阅实现，不适用于进程间通信。 范例12345678910111213// Class is typically registered b">
<meta name="keywords" content="java,guava">
<meta property="og:type" content="article">
<meta property="og:title" content="guava的eventBus时间总线">
<meta property="og:url" content="https://blog.xiezc.xyz/2019/01/22/java/guava的eventBus时间总线/index.html">
<meta property="og:site_name" content="xiezc的小站">
<meta property="og:description" content="[Google Guava] 11-事件总线原文链接 译文连接 译者：沈义扬 传统上，Java的进程内事件分发都是通过发布者和订阅者之间的显式注册实现的。设计EventBus就是为了取代这种显示注册方式，使组件间有了更好的解耦。EventBus不是通用型的发布-订阅实现，不适用于进程间通信。 范例12345678910111213// Class is typically registered b">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-04-04T14:19:29.308Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="guava的eventBus时间总线">
<meta name="twitter:description" content="[Google Guava] 11-事件总线原文链接 译文连接 译者：沈义扬 传统上，Java的进程内事件分发都是通过发布者和订阅者之间的显式注册实现的。设计EventBus就是为了取代这种显示注册方式，使组件间有了更好的解耦。EventBus不是通用型的发布-订阅实现，不适用于进程间通信。 范例12345678910111213// Class is typically registered b">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.xiezc.xyz/2019/01/22/java/guava的eventBus时间总线/">





  <title>guava的eventBus时间总线 | xiezc的小站</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8ae02d8cf311eabbae2621ff2d51a260";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xiezc的小站</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">xiezc的小站</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.xiezc.xyz/2019/01/22/java/guava的eventBus时间总线/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xiezc">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xiezc的小站">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">guava的eventBus时间总线</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-22T17:16:59+08:00">
                2019-01-22
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/01/22/java/guava的eventBus时间总线/" class="leancloud_visitors" data-flag-title="guava的eventBus时间总线">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="Google-Guava-11-事件总线"><a href="#Google-Guava-11-事件总线" class="headerlink" title="[Google Guava] 11-事件总线"></a>[Google Guava] 11-事件总线</h3><p><a href="http://code.google.com/p/guava-libraries/wiki/EventBusExplained" target="_blank" rel="noopener">原文链接</a> <a href="http://ifeve.com/google-guava-eventbus" target="_blank" rel="noopener">译文连接</a> <strong>译者：</strong>沈义扬</p>
<p>传统上，Java的<strong>进程内事件分发</strong>都是通过发布者和订阅者之间的显式注册实现的。设计<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/eventbus/EventBus.html" target="_blank" rel="noopener">EventBus</a>就是为了取代这种显示注册方式，使组件间有了更好的解耦。EventBus不是通用型的发布-订阅实现，不适用于进程间通信。</p>
<h2 id="范例"><a href="#范例" class="headerlink" title="范例"></a>范例</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Class is typically registered by the container.</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">EventBusChangeRecorder</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Subscribe</span> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">recordCustomerChange</span><span class="params">(ChangeEvent e)</span> </span>&#123;</span><br><span class="line">        recordChange(e.getChange());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// somewhere during initialization</span></span><br><span class="line">eventBus.register(<span class="keyword">new</span> EventBusChangeRecorder());</span><br><span class="line"><span class="comment">// much later</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">changeCustomer</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    ChangeEvent event = getChangeEvent();</span><br><span class="line">    eventBus.post(event);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="一分钟指南"><a href="#一分钟指南" class="headerlink" title="一分钟指南"></a>一分钟指南</h2><p>把已有的进程内事件分发系统迁移到EventBus非常简单。</p>
<h3 id="事件监听者-Listeners"><a href="#事件监听者-Listeners" class="headerlink" title="事件监听者[Listeners]"></a>事件监听者[Listeners]</h3><p>监听特定事件（如，CustomerChangeEvent）：</p>
<ul>
<li>传统实现：定义相应的事件监听者类，如CustomerChangeEventListener；</li>
<li>EventBus实现：以CustomerChangeEvent为唯一参数创建方法，并用<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/eventbus/Subscribe.html" target="_blank" rel="noopener">Subscribe</a>注解标记。</li>
</ul>
<p>把事件监听者注册到事件生产者：</p>
<ul>
<li>传统实现：调用事件生产者的registerCustomerChangeEventListener方法；这些方法很少定义在公共接口中，因此开发者必须知道所有事件生产者的类型，才能正确地注册监听者；</li>
<li>EventBus实现：在EventBus<strong>实例</strong>上调用<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/eventbus/EventBus.html#register(java.lang.Object" target="_blank" rel="noopener">EventBus.register(Object)</a>)方法；请保证事件生产者和监听者共享相同的EventBus<strong>实例</strong>。</li>
</ul>
<p>按事件超类监听（如，EventObject甚至Object）：</p>
<ul>
<li>传统实现：很困难，需要开发者自己去实现匹配逻辑；</li>
<li>EventBus实现：EventBus自动把事件分发给事件超类的监听者，并且允许监听者声明监听接口类型和泛型的通配符类型（wildcard，如 ? super XXX）。</li>
</ul>
<p>检测没有监听者的事件：</p>
<ul>
<li>传统实现：在每个事件分发方法中添加逻辑代码（也可能适用AOP）；</li>
<li>EventBus实现：监听<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/eventbus/DeadEvent.html" target="_blank" rel="noopener">DeadEvent</a>；EventBus会把所有发布后没有监听者处理的事件包装为DeadEvent（对调试很便利）。</li>
</ul>
<h3 id="事件生产者-Producers"><a href="#事件生产者-Producers" class="headerlink" title="事件生产者[Producers]"></a>事件生产者[Producers]</h3><p>管理和追踪监听者：</p>
<ul>
<li>传统实现：用列表管理监听者，还要考虑线程同步；或者使用工具类，如EventListenerList；</li>
<li>EventBus实现：EventBus内部已经实现了监听者管理。</li>
</ul>
<p>向监听者分发事件：</p>
<ul>
<li>传统实现：开发者自己写代码，包括事件类型匹配、异常处理、异步分发；</li>
<li>EventBus实现：把事件传递给 <a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/eventbus/EventBus.html#post(java.lang.Object" target="_blank" rel="noopener">EventBus.post(Object)</a>)方法。异步分发可以直接用EventBus的子类<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/eventbus/AsyncEventBus.html" target="_blank" rel="noopener">AsyncEventBus</a>。</li>
</ul>
<h2 id="术语表"><a href="#术语表" class="headerlink" title="术语表"></a>术语表</h2><p>事件总线系统使用以下术语描述事件分发：</p>
<table>
<thead>
<tr>
<th>事件</th>
<th>可以向事件总线发布的对象</th>
</tr>
</thead>
<tbody>
<tr>
<td>订阅</td>
<td>向事件总线注册<em>监听者</em>以接受事件的行为</td>
</tr>
<tr>
<td>监听者</td>
<td>提供一个<em>处理方法</em>，希望接受和处理事件的对象</td>
</tr>
<tr>
<td>处理方法</td>
<td>监听者提供的公共方法，事件总线使用该方法向监听者发送事件；该方法应该用Subscribe注解</td>
</tr>
<tr>
<td>发布消息</td>
<td>通过事件总线向所有匹配的监听者提供事件</td>
</tr>
</tbody>
</table>
<h2 id="常见问题解答-FAQ"><a href="#常见问题解答-FAQ" class="headerlink" title="常见问题解答[FAQ]"></a>常见问题解答[FAQ]</h2><p><strong>为什么一定要创建**</strong>EventBus<strong>**实例，而不是使用单例模式？</strong></p>
<p>EventBus不想给定开发者怎么使用；你可以在应用程序中按照不同的组件、上下文或业务主题分别使用不同的事件总线。这样的话，在测试过程中开启和关闭某个部分的事件总线，也会变得更简单，影响范围更小。</p>
<p>当然，如果你想在进程范围内使用唯一的事件总线，你也可以自己这么做。比如在容器中声明EventBus为全局单例，或者用一个静态字段存放EventBus，如果你喜欢的话。</p>
<p>简而言之，EventBus不是单例模式，是因为我们不想为你做这个决定。你喜欢怎么用就怎么用吧。</p>
<p><strong>可以从事件总线中注销监听者吗？</strong>  </p>
<p>当然可以，使用EventBus.unregister(Object)方法，但我们发现这种需求很少：</p>
<ul>
<li>大多数监听者都是在启动或者模块懒加载时注册的，并且在应用程序的整个生命周期都存在；</li>
<li>可以使用特定作用域的事件总线来处理临时事件，而不是注册/注销监听者；比如在请求作用域[request-scoped]的对象间分发消息，就可以同样适用请求作用域的事件总线；</li>
<li>销毁和重建事件总线的成本很低，有时候可以通过销毁和重建事件总线来更改分发规则。</li>
</ul>
<p><strong>为什么使用注解标记处理方法，而不是要求监听者实现接口？</strong></p>
<p>我们觉得注解和实现接口一样传达了明确的语义，甚至可能更好。同时，使用注解也允许你把处理方法放到任何地方，和使用业务意图清晰的方法命名。</p>
<p>传统的Java实现中，监听者使用方法很少的接口——通常只有一个方法。这样做有一些缺点:</p>
<ul>
<li>监听者类对给定事件类型，只能有单一处理逻辑；</li>
<li>监听者接口方法可能冲突；</li>
<li>方法命名只和事件相关（handleChangeEvent），不能表达意图（recordChangeInJournal）；</li>
<li>事件通常有自己的接口，而没有按类型定义的公共父接口（如所有的UI事件接口）。</li>
</ul>
<p>接口实现监听者的方式很难做到简洁，这甚至引出了一个模式，尤其是在Swing应用中，那就是用匿名类实现事件监听者的接口。比较以下两种实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ChangeRecorder</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">setCustomer</span><span class="params">(Customer cust)</span> </span>&#123;</span><br><span class="line">        cust.addChangeListener(<span class="keyword">new</span> ChangeListener() &#123;</span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">customerChanged</span><span class="params">(ChangeEvent e)</span> </span>&#123;</span><br><span class="line">                recordChange(e.getChange());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这个监听者类通常由容器注册给事件总线</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">EventBusChangeRecorder</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Subscribe</span> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">recordCustomerChange</span><span class="params">(ChangeEvent e)</span> </span>&#123;</span><br><span class="line">        recordChange(e.getChange());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第二种实现的业务意图明显更加清晰：没有多余的代码，并且处理方法的名字是清晰和有意义的。</p>
<p><strong>通用的监听者接口**</strong>Handler<t><strong>**怎么样？</strong></t></p>
<p>有些人已经建议过用泛型定义一个通用的监听者接口Handler<t>。这有点牵扯到Java类型擦除的问题，假设我们有如下这个接口：</t></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">interface</span> <span class="title">Handler</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">handleEvent</span><span class="params">(T event)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因为类型擦除，Java禁止一个类使用不同的类型参数多次实现同一个泛型接口（即不可能出现MultiHandler implements Handler<type1>, Handler<type2>）。这比起传统的Java事件机制也是巨大的退步，至少传统的Java Swing监听者接口使用了不同的方法把不同的事件区分开。</type2></type1></p>
<p><strong>EventBus**</strong>不是破坏了静态类型，排斥了自动重构支持吗？**</p>
<p>有些人被EventBus的register(Object) 和post(Object)方法直接使用Object做参数吓坏了。</p>
<p>这里使用Object参数有一个很好的理由：EventBus对事件监听者类型和事件本身的类型都不作任何限制。</p>
<p>另一方面，处理方法必须要明确地声明参数类型——期望的事件类型（或事件的父类型）。因此，搜索一个事件的类型引用，可以马上找到针对该事件的处理方法，对事件类型的重命名也会在IDE中自动更新所有的处理方法。</p>
<p>在EventBus的架构下，你可以任意重命名@Subscribe注解的处理方法，并且这类重命名不会被传播（即不会引起其他类的修改），因为对EventBus来说，处理方法的名字是无关紧要的。如果测试代码中直接调用了处理方法，那么当然，重命名处理方法会引起测试代码的变动，但使用EventBus触发处理方法的代码就不会发生变更。我们认为这是EventBus的特性，而不是漏洞：能够任意重命名处理方法，可以让你的处理方法命名更清晰。</p>
<p><strong>如果我注册了一个没有任何处理方法的监听者，会发生什么？</strong></p>
<p>什么也不会发生。</p>
<p>EventBus旨在与容器和模块系统整合，Guice就是个典型的例子。在这种情况下，可以方便地让容器/工厂/运行环境传递任意创建好的对象给EventBus的register(Object)方法。</p>
<p>这样，任何容器/工厂/运行环境创建的对象都可以简便地通过暴露处理方法挂载到系统的事件模块。</p>
<p><strong>编译时能检测到**</strong>EventBus<strong>**的哪些问题？</strong></p>
<p>Java类型系统可以明白地检测到的任何问题。比如，为一个不存在的事件类型定义处理方法。</p>
<p><strong>运行时往**</strong>EventBus<strong>**注册监听者，可以立即检测到哪些问题？</strong></p>
<p>一旦调用了register(Object) 方法，EventBus就会检查监听者中的处理方法是否结构正确的[well-formedness]。具体来说，就是每个用@Subscribe注解的方法都只能有一个参数。</p>
<p>违反这条规则将引起IllegalArgumentException（这条规则检测也可以用APT在编译时完成，不过我们还在研究中）。</p>
<p><strong>哪些问题只能在之后事件传播的运行时才会被检测到？</strong></p>
<p>如果组件传播了一个事件，但找不到相应的处理方法，EventBus<em>可能</em>会指出一个错误（通常是指出@Subscribe注解的缺失，或没有加载监听者组件）。</p>
<p><em>请注意这个指示并不一定表示应用有问题。一个应用中可能有好多场景会故意忽略某个事件，尤其当事件来源于不可控代码时</em></p>
<p>你可以注册一个处理方法专门处理DeadEvent类型的事件。每当EventBus收到没有对应处理方法的事件，它都会将其转化为DeadEvent，并且传递给你注册的DeadEvent处理方法——你可以选择记录或修复该事件。</p>
<p><strong>怎么测试监听者和它们的处理方法？</strong></p>
<p>因为监听者的处理方法都是普通方法，你可以简便地在测试代码中模拟EventBus调用这些方法。</p>
<p><strong>为什么我不能在**</strong>EventBus<strong><strong>上使用</strong></strong>&lt;<strong>泛型</strong>魔法<strong><strong>&gt;</strong></strong>？**</p>
<p>EventBus旨在很好地处理一大类用例。我们更喜欢针对大多数用例直击要害，而不是在所有用例上都保持体面。</p>
<p>此外，泛型也让EventBus的可扩展性——让它有益、高效地扩展，同时我们对EventBus的增补不会和你们的扩展相冲突——成为一个非常棘手的问题。</p>
<p>如果你真的很想用泛型，EventBus目前还不能提供，你可以提交一个问题并且设计自己的替代方案。</p>
<p><strong>原创文章，转载请注明：</strong> 转载自<a href="http://ifeve.com/" target="_blank" rel="noopener">并发编程网 – ifeve.com</a><strong>本文链接地址:</strong> <a href="http://ifeve.com/google-guava-eventbus/" target="_blank" rel="noopener">[Google Guava] 11-事件总线</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/guava/" rel="tag"># guava</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/17/java/Jdk8到jdk11 Springboot 踩坑指南/" rel="next" title="Jdk8到jdk11 Springboot 踩坑指南">
                <i class="fa fa-chevron-left"></i> Jdk8到jdk11 Springboot 踩坑指南
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/22/docker/docker-compose部署springcloud踩的坑/" rel="prev" title="docker-compose部署springcloud踩的坑">
                docker-compose部署springcloud踩的坑 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">xiezc</p>
              <p class="site-description motion-element" itemprop="description">主要一些技术文章, 有些文章是转载的</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">72</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Google-Guava-11-事件总线"><span class="nav-number">1.</span> <span class="nav-text">[Google Guava] 11-事件总线</span></a></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#范例"><span class="nav-number"></span> <span class="nav-text">范例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一分钟指南"><span class="nav-number"></span> <span class="nav-text">一分钟指南</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#事件监听者-Listeners"><span class="nav-number">1.</span> <span class="nav-text">事件监听者[Listeners]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#事件生产者-Producers"><span class="nav-number">2.</span> <span class="nav-text">事件生产者[Producers]</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#术语表"><span class="nav-number"></span> <span class="nav-text">术语表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常见问题解答-FAQ"><span class="nav-number"></span> <span class="nav-text">常见问题解答[FAQ]</span></a></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xiezc</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("eRAHvO0xVYwckgdXIVpfugRG-gzGzoHsz", "57lKp708hde92YeG1xX9MQj1");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
